<template>
	<view class="container">
		<u-top-tips ref="uTips"></u-top-tips>
		<view class="header">
			<input type="text" placeholder="请输入标题" v-model="title" />
			<view class="look" hover-class="touch" hover-start-time="0" hover-stay-time="300" @tap="look">预览</view>
			<view class="push" hover-class="touch" hover-start-time="0" hover-stay-time="300" @tap="push">发布</view>
		</view>
		<view class="uUpload">
			<view class="uUpload-item" hover-class="touch" hover-start-time="0" hover-stay-time="300" @tap="uUploadImage">
				<u-icon v-if="!bannerUrl" name="photo" size="60"></u-icon>
				<text v-if="!bannerUrl" style="margin-top: 30rpx">点击上传封面图片</text>
				<view class="banner" v-if="bannerUrl"><ImageLoad :src="bannerUrl" borderRadius="10" /></view>
			</view>
			<view class="uUpload-item" hover-class="touch" hover-start-time="0" hover-stay-time="300" @tap="uUploadVideo">
				<u-icon class="remove" v-if="video.url" @tap.native.stop="removeVideo" name="close-circle" size="40"></u-icon>
				<u-icon v-if="!video.url" :name="percent > 0 ? 'close-circle' : 'play-circle'" size="60"></u-icon>
				<text v-if="!video.url" style="margin-top: 30rpx">{{ percent > 0 ? (percent === 100 ? '正在转码，点击取消' : '正在上传，点击取消') : '点击上传视频(可选)' }}</text>
				<view class="banner" v-if="video.url"><video class="video" :src="video.url"></video></view>
				<u-line-progress v-if="percent > 0" style="width: 100%" :striped="true" :percent="percent" :striped-active="true"></u-line-progress>
			</view>
		</view>
		<view class="signUp" v-if="hasOfficial">
			<u-form :model="form" ref="uForm">
				<u-form-item :label-width="400" label="是否为报名参加链接"><u-switch slot="right" active-color="#FED36B" v-model="switchVal"></u-switch></u-form-item>
				<u-form-item v-if="switchVal" :label-width="200" label="联系人姓名"><u-input v-model="form.name" /></u-form-item>
				<u-form-item v-if="switchVal" :label-width="200" label="微信号"><u-input v-model="form.weixinCode" /></u-form-item>
				<u-form-item v-if="switchVal" :label-width="200" label="联系方式"><u-input v-model="form.contact" /></u-form-item>
			</u-form>
		</view>
		<view class="toolbar" @tap="format">
			<view :class="formats.header === 1 ? 'ql-active' : ''" class="iconfont" style="font-weight: bold" data-name="header" :data-value="1">标</view>
			<view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold"></view>
			<view class="mark"></view>
			<view :class="formats.align === 'center' ? 'ql-active' : ''" class="iconfont icon-juzhongduiqi" data-name="align" data-value="center"></view>
			<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi" data-name="align" data-value="right"></view>
			<view class="mark"></view>
			<view :class="formats.list === 'ordered' ? 'ql-active' : ''" class="iconfont icon-youxupailie" data-name="list" data-value="ordered"></view>
			<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie" data-name="list" data-value="bullet"></view>
			<view class="mark"></view>
			<view class="iconfont icon-charutupian" @tap="insertImage"></view>
			<view class="mark"></view>
			<view class="iconfont icon-undo" @tap="undo"></view>
			<view class="iconfont icon-redo" @tap="redo"></view>
		</view>
		<editor
			id="editor"
			class="ql-container"
			placeholder="开始输入..."
			showImgSize
			showImgToolbar
			showImgResize
			@statuschange="onStatusChange"
			:read-only="false"
			@ready="onEditorReady"
			@input="input"
		></editor>
	</view>
</template>

<script>
import { log } from 'util'
let uploadTask = null
export default {
	data() {
		return {
			formats: {},
			hasOfficial: false,
			form: {
				name: '',
				weixinCode: '',
				contact: '',
			},
			switchVal: false,
			bannerUrl: '',
			video: {
				url: '',
				width: 0,
				height: 0,
			},
			title: '',
			id: 0,
			type: '',
			percent: 0,
			detailType: '',
			editorCtx: {},
		}
	},
	onLoad(option) {
		this.id = option.id
		console.log(option)
		this.type = option.type
		this.detailType = this.type === 'note' ? 'noteEditor' : 'topicEditor'
		if (this.type === 'hasOfficial') this.hasOfficial = true
		if (this.type === 'note') {
			uni.setNavigationBarTitle({
				title: '发布新手账',
			})
		}
		const detail = uni.getStorageSync(this.detailType)
		if (!detail) {
			uni.setStorageSync(this.detailType, {})
		}
		this.title = detail.title
		this.bannerUrl = detail.bannerUrl
		this.video = detail.video ? detail.video : { url: '', width: 0, height: 0 }
	},
	watch: {
		title: function (title) {
			const editor = uni.getStorageSync(this.detailType)
			editor.title = title
			uni.setStorageSync(this.detailType, editor)
		},
		bannerUrl: function (bannerUrl) {
			const editor = uni.getStorageSync(this.detailType)
			editor.bannerUrl = bannerUrl
			uni.setStorageSync(this.detailType, editor)
		},
		video: function (video) {
			console.log(video)
			const editor = uni.getStorageSync(this.detailType)
			editor.video = video
			uni.setStorageSync(this.detailType, editor)
		},
	},
	methods: {
		uUploadImage: async function () {
			const [data, err] = await this.awaitWarp(this.chooseImage())
			if (err) {
				this.$refs.uTips.show({
					title: '非法内容',
					type: 'error',
					duration: '2000',
				})
				return
			}
			this.bannerUrl = data
		},
		uUploadVideo: async function () {
			if (this.video.url) return
			if (this.percent > 0) {
				uploadTask.abort()
				this.percent = 0
				return
			}
			uni.chooseVideo({
				count: 1,
				success: (res) => {
					if (res.size / 1024 / 1024 > 200) {
						this.$refs.uTips.show({
							title: '视频大小不能超过200M',
							type: 'error',
							duration: '2000',
						})
						return
					}
					uploadTask = uni.uploadFile({
						url: this.api.upload,
						filePath: res.tempFilePath,
						name: 'file',
						success: (data) => {
							this.percent = 0
							if (JSON.parse(data.data).errorCode === 'hasIllegalContent') {
								this.$refs.uTips.show({
									title: '非法内容',
									type: 'error',
									duration: '2000',
								})
								return
							}
							this.$refs.uTips.show({
								title: '视频上传成功',
								type: 'warning',
								duration: '2000',
							})

							this.video = {
								url: JSON.parse(data.data).fileUrl,
								width: res.width,
								height: res.height,
							}
						},
						fail: () => {
							this.$refs.uTips.show({
								title: '视频上传失败',
								type: 'warning',
								duration: '2000',
							})
						},
					})
					uploadTask.onProgressUpdate((res) => {
						this.percent = res.progress
					})
				},
			})
		},
		removeVideo: function () {
			this.video = {
				url: '',
				width: '',
				height: '',
			}
		},
		onEditorReady() {
			uni.createSelectorQuery()
				.select('#editor')
				.context((res) => {
					this.editorCtx = res.context
					const detail = uni.getStorageSync(this.detailType)
					if (detail.html) {
						this.editorCtx.setContents({
							html: detail.html,
						})
					}
				})
				.exec()
		},
		undo() {
			this.editorCtx.undo()
		},
		redo() {
			this.editorCtx.redo()
		},
		format(e) {
			let { name, value } = e.target.dataset
			if (!name) return
			this.editorCtx.format(name, value)
		},
		onStatusChange(e) {
			const formats = e.detail
			this.formats = formats
		},
		input(e) {
			const editor = uni.getStorageSync(this.detailType)
			editor.html = e.detail.html
			uni.setStorageSync(this.detailType, editor)
		},
		insertImage: async function () {
			const data = await this.chooseImage()
			this.editorCtx.insertImage({
				src: data,
				alt: '图像',
			})
		},
		filter: function () {
			return new Promise((resolve, reject) => {
				if (!this.title) {
					this.$refs.uTips.show({
						title: '请输入输入标题',
						type: 'warning',
						duration: '2000',
					})
					return
				}
				if (!this.bannerUrl) {
					this.$refs.uTips.show({
						title: '请上传封面图片',
						type: 'warning',
						duration: '2000',
					})
					return
				}
				if (this.switchVal && (!this.form.name || !this.form.weixinCode || !this.form.contact)) {
					this.$refs.uTips.show({
						title: '请完善活动信息',
						type: 'warning',
						duration: '2000',
					})
					return
				}
				resolve()
			})
		},
		look: async function () {
			await this.filter()
			const item = {
				coverUrl: this.bannerUrl,
				title: this.title,
				contentType: 'dom',
				type: 'test',
			}
			if (this.video.url) {
				item.video = this.video
			}

			this.editorCtx.getContents({
				success: (res) => {
					item.dom = res.html
					this.$Router.push({ name: 'topicDetail', query: { item: JSON.stringify(item) } })
				},
			})
		},
		push: async function () {
			await this.filter()
			this.delayFunc(() => {
				const item = {
					deviceUuid: this.deviceUuid,
					coverUrl: this.bannerUrl,
					title: this.title,
					currentTopicId: this.id,
				}
				if (this.video.url) {
					item.video = this.video
				}
				if (this.switchVal) {
					item.hasRegisterLink = true
					item.organizer = this.form
				}
				this.editorCtx.getContents({
					success: async (res) => {
						item.content = res.html
						const api = this.type === 'note' ? 'addNote' : 'addTopic'
						const [data, err] = await this.awaitWarp(this.$post(this.api[api], item))
						if (err) {
							this.$refs.uTips.show({
								title: '网络请求失败',
								type: 'warning',
								duration: '2000',
							})
							return
						}
						if (data.errorCode === 'hasIllegalContent') {
							this.$refs.uTips.show({
								title: '非法内容',
								type: 'error',
								duration: '2000',
							})
							return
						}
						this.$refs.uTips.show({
							title: '发布成功',
							type: 'success',
							duration: '2000',
						})
						uni.setStorageSync(this.detailType, {})
						setTimeout(() => {
							if (this.type === 'note') {
								getApp().globalData.noteLoadData = true
								this.$Router.pushTab({ name: 'note' })
							} else {
								getApp().globalData.topicLoadData = true
								this.$Router.pushTab({ name: 'topic' })
							}
						}, 2000)
					},
				})
			})
		},
	},
}
</script>

<style scoped lang="stylus">
@import '../../common/css/editor-icon.css'

.container
	width 100vw
	height auto
	min-height 100vh
	display flex
	flex-direction column
	background white

	.header
		display flex
		height 8vh
		align-items center
		margin-left 20rpx

		input
			height 8vh
			padding-left 20rpx
			font-size 40rpx
			border-bottom 2rpx solid #DFE1E5
			width 450rpx
			box-sizing border-box

		.push
			position fixed
			right 20rpx
			width 100rpx
			height 60rpx
			font-size 30rpx
			background #FB864E
			border-radius 20rpx
			line-height 60rpx
			text-align center
			color white
			transition all 0.3s
			z-index 2

		.look
			position fixed
			right 140rpx
			width 100rpx
			height 60rpx
			font-size 30rpx
			background orange
			border-radius 20rpx
			line-height 60rpx
			text-align center
			color white
			transition all 0.3s
			z-index 2

	.uUpload
		width 750rpx
		height 230rpx
		display flex

		.uUpload-item
			width 345rpx
			height 230rpx
			margin-left 20rpx
			background #F4F5F6
			margin-top 20rpx
			border-radius 20rpx
			display flex
			flex-direction column
			justify-content center
			align-items center
			color #555555
			transition all 0.3s
			position relative

			.banner
				position relative
				width 100%
				height 100%
				overflow hidden
				transform translate3d(0, 0, 0)
				border-radius 20rpx

				.video
					width 100%
					height 100%

			.remove
				position absolute
				right 20rpx
				top 20rpx
				color red
				z-index 1

	.signUp
		width 750rpx
		padding 30rpx
		box-sizing border-box

	.iconfont
		display inline-block
		width 75rpx
		height 70rpx
		font-size 40rpx
		line-height 70rpx
		text-align center

	.toolbar
		box-sizing border-box
		height 8vh
		line-height 8vh
		border-bottom 2rpx solid #DFE1E5
		margin-left 20rpx

		.mark
			height 40rpx
			width 2rpx
			background #DFE1E5
			display inline-block
			transform translateY(7.5rpx)

	.ql-container
		box-sizing border-box
		width 750rpx
		min-height calc(84vh - 200rpx)
		height auto
		background #fff
		font-size 30rpx
		line-height 1.5
		padding 20rpx

	.ql-active
		background #FED166

	.editorImg
		display block
</style>
